﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace 串口助手
{
    /// <summary>
    /// 处理串口助手的日志记录
    /// </summary>
    class CommLog
    {
        private string logFileName; // 日志文件名

        /// <summary>
        /// 点击按钮时记录日志
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        public void ButtonLogClick(object sender, EventArgs e)
        {
            if (sender is ToolStripButton button)
            {
                if (button.ToolTipText == "记录log")
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog
                    {
                        Filter = "log|*.log|文本|*.txt",
                        FileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-s")
                    };

                    // 显示保存对话框
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        StartLogging(button, saveFileDialog.FileName);
                    }
                }
                else
                {
                    StopLogging(button);
                }
            }
        }

        private void StartLogging(ToolStripButton button, string fileName)
        {
            button.ToolTipText = "关闭log"; // 更新按钮提示
            button.BackColor = Color.LimeGreen; // 设置按钮颜色
            logFileName = fileName; // 获取文件名

            using (StreamWriter stream = new StreamWriter(logFileName))
            {
                stream.WriteLine("串口助手LOG");
                stream.WriteLine(DateTime.Now.ToString("yyyy-MM-dd-HH-mm-s"));
                stream.WriteLine("******************************");
            }
        }

        private void StopLogging(ToolStripButton button)
        {
            button.ToolTipText = "记录log"; // 更新按钮提示
            button.BackColor = Color.Transparent; // 重置按钮颜色
            logFileName = null; // 清空文件名
        }

        /// <summary>
        /// 向日志文件写入消息
        /// </summary>
        /// <param name="msg">要写入的消息</param>
        public void LogWriteMsg(string msg)
        {
            if (string.IsNullOrEmpty(logFileName)) return; // 如果文件名为空，则返回

            try
            {
                using (StreamWriter stream = new StreamWriter(logFileName, true))
                {
                    stream.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {msg}"); // 写入时间戳和消息
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"写入日志失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
